package com.loie.xcx.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.loie.xcx.model.bo.TokenInfoBO;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhl
 */
public class TokenUtils {

    private static final long EXPIRE_DATE = 60 * 60 * 1000;
    private static final String TOKEN_SECRET = "ZHfasfhuaUUHufguGuwu2021LOIE";
    private static final String TOKEN_USER = "user";

    public static String token(String username) {

        String token;
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String, Object> header = new HashMap<>(2);
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            //携带username，password信息，生成签名
            token = JWT.create().withHeader(header).withClaim(TOKEN_USER, username).withClaim("password", "LOIE").withExpiresAt(date).withIssuedAt(new Date(System.currentTimeMillis())).sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return token;
    }

    public static boolean verify(TokenInfoBO bo) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(bo.getToken());
            bo.setUser(jwt.getClaim(TOKEN_USER).asString());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}